package com.tvata.smarttv.ktv;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.tvata.smarttv.ktv.aiopen.AIOpenService;
import com.vatata.tools.DeviceIDUtil;
import com.vatata.wae.WaeSettings;
import com.vatata.wae.cloud.launcher.TvLauncherActivity;
import com.vatata.wae.tvapp.TvAppActivity;

import net.fs.client.FSClient;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends TvLauncherActivity {

	private static final String[] PERMISSIONS;
	private static final int REQUEST_CODE = 23012;

	static {
		PERMISSIONS = new String[] {
				Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.WRITE_EXTERNAL_STORAGE,
		};
	}

	@RequiresApi(api = Build.VERSION_CODES.M)
	protected void requestPermissions() {
		List<String> needPermList = new ArrayList<>();

		for (String p: PERMISSIONS) {
			int r = checkSelfPermission(p);

			if (r == PackageManager.PERMISSION_DENIED) {
				needPermList.add(p);
			} else if(r != PackageManager.PERMISSION_GRANTED){
				needPermList.add(p);
			} else {
				onPermissionGranted(p);
			}
		}

		if (needPermList.size() > 0) {
			// Manifest.permission.RECORD_AUDIO
			String[] ps = needPermList.toArray(new String[needPermList.size()]);
			requestPermissions(ps, REQUEST_CODE);
		}

//		if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q) {
//			if (!Environment.isExternalStorageManager()) {
//				Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
//				startActivity(intent);
//			}
//		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

		if (requestCode != REQUEST_CODE) {
			return;
		}

		for (int i=0; i<permissions.length; i++) {
			String permission = permissions[i];
			int result = grantResults[i];

			if (result == PackageManager.PERMISSION_GRANTED) {
				onPermissionGranted(permission);
			} else if (result == PackageManager.PERMISSION_DENIED) {
				onPermissionDenied(permission);
			}
		}
	}

	protected void onPermissionGranted(String permission) {
	}

	protected void onPermissionDenied(String permission) {
	}

	@RequiresApi(api = Build.VERSION_CODES.M)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestPermissions();
		Intent intent = new Intent(this, AIOpenService.class);
		intent.setAction("com.peasun.aispeech.action.ktv");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			startForegroundService(intent);
		} else {
			startService(intent);
		}

		// KTV 519
		//portal_page = "portal_32/html/mainplus_pro.html";
		//portal_config = "download/ZIP_CONFIG_32.xml";
		//this.use_Home_Url = "tva://139.99.63.222:16314/";
		//this.use_Home_Url = "tva://192.168.3.76:16310/";//lawrence演示 http://10.255.192.106:16310 tva://39.106.128.8:5024/

		// KTV 521 加密版
		portal_page = "portal_46/html/mainplus_max.html";
		portal_config = "download/ZIP_CONFIG_46.xml";
		//this.use_Home_Url = "tvas://newktv.kalaokay.com:16315/";
		this.use_Home_Url = "tvas://jazpiperapi.tvata.com:16315/";

		// KTV 313
//		portal_page = "portal_29/html/mainplus.html";
//		portal_config = "download/ZIP_CONFIG_29.xml";
//		this.use_Home_Url = "tva://newktv.kalaokay.com:16314/";
//		this.use_Home_Url = "tva://139.99.63.222:16314/";

//		FSClient.localport_start = 22278;
//		int localport = FSClient.getStandaloneAccelClient( "newktv.kalaokay.com", 16310, 16314 );
//		this.use_Home_Url = "tva://127.0.0.1:"+ localport + "/";

		//this.use_Startup_Url = "file:///android_asset/html/start/index.html";//离线版
		//this.use_Startup_Url = "file:///android_asset/html/loading/index.html";//KTV PRO

//		SharedPreferences sp = getSharedPreferences("Preferences", Activity.MODE_PRIVATE);
//		String new_features = sp.getString("new_features", "");
//		Log.d("wae", "get new_features: " + new_features);
//
//		if ( new_features != null && new_features.isEmpty() == false ) {
////			portal_page = "portal_26/html/main.html";
////			portal_config = "download/ZIP_CONFIG_26.xml";
//			this.use_Startup_Url = "file:///android_asset/html/start/index.html";
//
//			TvAppActivity.config_name = "d.xml";
//			Log.d("wae", "get new_features enabled! " + new_features);
//		} else {
////			TvAppActivity.config_name = "appv2.xml";
//			this.use_Startup_Url = "file:///android_asset/html/start/index.html";
//		}

		//TvAppActivity.config_name = "yang.xml";//离线版
		//TvAppActivity.config_name = "pro.xml";//KTV PRO
		// TvAppActivity.config_name = "max_dist.xml";//KTV max dist
		TvAppActivity.config_name = "max_dist_vps.xml";//KTV max dist vps

		File debugpage = new File( "/sdcard/tva/debug/start/index.html" );
		if ( debugpage.exists() )
			this.use_Startup_Url = "file:///sdcard/tva/debug/start/index.html";

//		String debug_log = sp.getString("debug_log", "");
//		Log.d("wae", "get debug_log: " + debug_log);

//		if ( debug_log != null && debug_log.isEmpty() == false ) {
//			WaeWebChromeClient.isOutputConsoleMessage = true;
//		}
		WaeSettings.isOutputConsoleMessage = true;

//		WaeSettings.s().loadmode = WaeSettings.LOADMODE.NO_BLOCKING;
//		WaeSettings.s().tvaLoaderUrl = "file:///android_asset/html/start/load_local.html";


//		TvAppActivity.config_name = "appd.xml";

		WaeSettings.s().hideTvaUpdateProgress = true;
//		this.use_Home_Url = "tvas://hmazucg.logicdn.com:8443/";
//		portal_page = "portal_26/html/main.html";
//		portal_config = "download/ZIP_CONFIG_26.xml";
//		TvAppActivity.config_name = "d.xml";
//		this.use_Startup_Url = "file:///android_asset/html/start/index.html";


//		DeviceIDUtil.external_device_id = "m9d1589d98d53";

//		this.use_Home_Url = "tva://bo.fengsui.com.tw:10248/host/host79/";
//		this.use_Startup_Url = "tva://media.tvata.com/wae/utils/checkkey.xml";

//		this.use_Home_Url = "tva://139.99.63.222:16310/";
//		this.use_Home_Url = "tva://10.0.1.231:16314/";
//
//		PlayerActivity.default_pkgurl = "tva://media.tvata.com/wae3/player/mobplayer.xml";

		WaeSettings.s().uimode = WaeSettings.FORCE_TV_UI.UI1080;

//		WaeSettings.s().forceTvaUpdateInForegrond = false ;

		WaeSettings.s().loadmode = WaeSettings.LOADMODE.FAST;

		DeviceIDUtil deviceIDUtil = new  DeviceIDUtil(this);
		for( int i =0; i<DeviceIDUtil.deviceid_order.length;i++ ) {
			log("DeviceIDUtil.deviceid_order " + i + " : " + DeviceIDUtil.deviceid_order[i] );
		}

//		DeviceIDUtil.external_device_id = "m900eb3268ca0";
		deviceIDUtil.setDeivceIDType("cache,lan,wlan");

//		WaeSettings.s().setWebViewUserAgent( "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25");

		File cachedir = new File(  "/sdcard/vodcache"  );

		if ( !cachedir.isDirectory() ) {
			cachedir.mkdir();
		}
		WaeSettings.s().enableExtraMediaTracker = true;

//		saveDebugLogcatInSdcard();

//		WaeWebChromeClient.isOutputConsoleMessage = true;

		super.onCreate(savedInstanceState);

		WaeSettings.s().actionForSystemBar = WaeSettings.ActionForSystemBar.FORCE_HIDE;
	}


	private int backCount;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		Log.d("TvLauncher", "StartupActivity onkeydown " + keyCode );
		if (keyCode == KeyEvent.KEYCODE_BACK
				|| keyCode == KeyEvent.KEYCODE_ESCAPE) {

			if(backCount >= 10 ) {
				backCount = 0;
			}

			if ( this.mainWebView != null ) {
				Log.d("TvLauncher", "StartupActivity onkeydown go back " + keyCode );
				if ( mainWebView.canGoBack() ) {
					Log.d("TvLauncher", "StartupActivity mainWebView go back "  );
					mainWebView.goBack();
				}
				else {
					Log.d("TVLauncher", "StartupActivity onkeydown can not back " + backCount );
					if(backCount == 0 ) {
						Toast.makeText(this, "Press Back again to exit...", Toast.LENGTH_LONG).show();
					} else if ( backCount > 0 ) {
						this.finish();
					}
				}
			}
			backCount ++;
			return true;
		}
		else {
			backCount = 0;
		}

		return super.onKeyDown(keyCode, event);
	}

}
